<?php

namespace App\Console\Commands\Wanggui;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Service\OpenShop\Feishu\MapService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class CacheSyncDistrictAll extends Command
{
    const SCOPE_ON  = 1;
    const SCOPE_OFF = 2;

    const CATALOGUE = 'WANGGUI';
    /**
     * The name and signature of the console command.
     * scope  缓存范围
     * [php artisan wanggui:cache-sync-district --scope=all] 缓存所有的数据
     * [php artisan wanggui:cache-sync-district --scope=city --value=苏州市] 缓存指定的数据
     * @var string
     */
    protected $signature = 'wanggui:cache-sync-district';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步所有地区网规缓存';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '500M');
        $res          = GuanyuanDataService::districtVolume();
        $fixed        = self::fixed();
        $provinceData = $cityData = $areaData = [];
        $total        = [
            'shopTotalNum'            => 0,//门店总数
            'capacityTotalNum'        => 0,//累计容量
            'businessShopTotalNum'    => 0,//累计在营门店数
            'siteShopTotalNum'        => 0,//累计选址中门店数
            'prepareShopTotalNum'     => 0,//累计筹备中门店数
            'remainingPointTotalNum'  => 0,//累计剩余点位
            'provincePenetrationRate' => 0,//省级覆盖率
            'provinceTotalNum'        => 0,//省数量
            'cityPenetrationRate'     => 0,//城市覆盖率
            'cityTotalNum'            => 0,//城市数量
        ];
        foreach ($res as $v) {
            //省
            if (isset($provinceData[$v['省']])) {
                $provinceData[$v['省']]['capacity']          = $provinceData[$v['省']]['capacity'] + $v['容量'];
                $provinceData[$v['省']]['businessShopNum']   = $provinceData[$v['省']]['businessShopNum'] + $v['累计在营门店数'];
                $provinceData[$v['省']]['siteShopNum']       = $provinceData[$v['省']]['siteShopNum'] + $v['选址中门店数'];
                $provinceData[$v['省']]['prepareShopNum']    = $provinceData[$v['省']]['prepareShopNum'] + $v['筹备中门店数'];
                $provinceData[$v['省']]['remainingPointNum'] = $provinceData[$v['省']]['remainingPointNum'] + $v['剩余点位'];
                $provinceData[$v['省']]['shopNum']           = $provinceData[$v['省']]['shopNum'] + $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
            } else {
                $provinceData[$v['省']]['province']          = $v['省'];
                $provinceData[$v['省']]['capacity']          = $v['容量'];
                $provinceData[$v['省']]['businessShopNum']   = $v['累计在营门店数'];
                $provinceData[$v['省']]['siteShopNum']       = $v['选址中门店数'];
                $provinceData[$v['省']]['prepareShopNum']    = $v['筹备中门店数'];
                $provinceData[$v['省']]['remainingPointNum'] = $v['剩余点位'];
                $provinceData[$v['省']]['shopNum']           = $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
            }
            //市
            if (isset($cityData[$v['市']])) {
                $cityData[$v['市']]['capacity']          = $cityData[$v['市']]['capacity'] + $v['容量'];
                $cityData[$v['市']]['businessShopNum']   = $cityData[$v['市']]['businessShopNum'] + $v['累计在营门店数'];
                $cityData[$v['市']]['siteShopNum']       = $cityData[$v['市']]['siteShopNum'] + $v['选址中门店数'];
                $cityData[$v['市']]['prepareShopNum']    = $cityData[$v['市']]['prepareShopNum'] + $v['筹备中门店数'];
                $cityData[$v['市']]['remainingPointNum'] = $cityData[$v['市']]['remainingPointNum'] + $v['剩余点位'];
                $cityData[$v['市']]['shopNum']           = $cityData[$v['市']]['shopNum'] + $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
            } else {
                $cityData[$v['市']]['province']          = $v['省'];
                $cityData[$v['市']]['city']              = $v['市'];
                $cityData[$v['市']]['capacity']          = $v['容量'];
                $cityData[$v['市']]['businessShopNum']   = $v['累计在营门店数'];
                $cityData[$v['市']]['siteShopNum']       = $v['选址中门店数'];
                $cityData[$v['市']]['prepareShopNum']    = $v['筹备中门店数'];
                $cityData[$v['市']]['remainingPointNum'] = $v['剩余点位'];
                $cityData[$v['市']]['shopNum']           = $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
            }
            //区
            $areaData[$v['区']]['province']          = $v['省'];
            $areaData[$v['区']]['city']              = $v['市'];
            $areaData[$v['区']]['area']              = $v['区'];
            $areaData[$v['区']]['capacity']          = $v['容量'];
            $areaData[$v['区']]['businessShopNum']   = $v['累计在营门店数'];
            $areaData[$v['区']]['siteShopNum']       = $v['选址中门店数'];
            $areaData[$v['区']]['prepareShopNum']    = $v['筹备中门店数'];
            $areaData[$v['区']]['remainingPointNum'] = $v['剩余点位'];
            $areaData[$v['区']]['shopNum']           = $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
            $areaData[$v['区']]['penetrationRate']   = $v['容量'] > 0 && ($v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数']) > 0 ?
                round(($v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数']) * 100 / $v['容量'], 2) . "%" : 0;//渗透率 = 门店总数/网规容量
            //总量
            $total['capacityTotalNum']       = $total['capacityTotalNum'] + $v['容量'];
            $total['businessShopTotalNum']   = $total['businessShopTotalNum'] + $v['累计在营门店数'];
            $total['siteShopTotalNum']       = $total['siteShopTotalNum'] + $v['选址中门店数'];
            $total['prepareShopTotalNum']    = $total['prepareShopTotalNum'] + $v['筹备中门店数'];
            $total['remainingPointTotalNum'] = $total['remainingPointTotalNum'] + $v['剩余点位'];
            $total['shopTotalNum']           = $total['shopTotalNum'] + $v['累计在营门店数'] + $v['选址中门店数'] + $v['筹备中门店数'];//门店总数 = 营业中门店+选址中门店+筹备中门店
        }
        if ($provinceData) {
            $provinceShopTotalNum             = array_sum(array_column($provinceData, 'shopNum'));
            $provinceCapacity                 = array_sum(array_column($provinceData, 'capacity'));
            $total['provincePenetrationRate'] = $provinceShopTotalNum > 0 && $provinceCapacity > 0 ?
                round($provinceShopTotalNum * 100 / $provinceCapacity, 2) . "%" : 0;//渗透率 = 门店总数/网规容量
            $total['provinceTotalNum']        = count($provinceData);
            $provinceData                     = MapService::dataDeal($provinceData);
        }
        $region = self::getCityAdcodeAndLocalPoint();
        if ($cityData) {
            $cityShopTotalNum             = array_sum(array_column($cityData, 'shopNum'));
            $cityCapacity                 = array_sum(array_column($cityData, 'capacity'));
            $total['cityPenetrationRate'] = $cityShopTotalNum > 0 && $cityCapacity > 0 ?
                round($cityShopTotalNum * 100 / $cityCapacity, 2) . "%" : 0;//渗透率 = 门店总数/网规容量
            $total['cityTotalNum']        = count($cityData);
            $cityRankData                 = MapService::dataDeal($cityData);
            $cityData                     = [];
            foreach ($cityRankData as $v) {
                $province = $v['province'];
                $city     = $v['city'];
                unset($v['province']);
                unset($v['city']);
                $cityData[$province][$city] = $v;

                if ($areaData) {
                    foreach ($areaData as $vv) {
                        $provinceChild = $vv['province'];
                        $cityChild     = $vv['city'];
                        $areaChild     = $vv['area'];
                        if ($province == $provinceChild && $cityChild == $city) {
                            unset($vv['province']);
                            unset($vv['city']);
                            unset($vv['area']);
                            $cityData[$province][$city]['child'][$areaChild] = $vv;
                        }
                    }

                    $districtShopTotalNum       = array_sum(array_column($cityData[$province][$city]['child'], 'shopNum'));
                    $districtCapacity           = array_sum(array_column($cityData[$province][$city]['child'], 'capacity'));
                    $cityData[$province][$city] = array_merge(
                        $cityData[$province][$city], [
                            'totalDistrict'           => count($cityData[$province][$city]['child']),//每个市对应下属区数量
                            'districtPenetrationRate' => $districtShopTotalNum > 0 && $districtCapacity > 0 ?
                                round($districtShopTotalNum * 100 / $districtCapacity, 2) . "%" : 0,//渗透率 = 门店总数/网规容量
                        ]
                    );

                    $infoCity = MapService::mapDataList($city, '', '');

                    collect($infoCity)->each(function ($data, $blot) use (&$cityData, $province, $city) {
                        $cityData[$province][$city][$blot] = count($data);
                    });

                    if (in_array($city, array_keys($fixed))) {
                        $cityData[$province][$city]['recommendArea'] = $fixed[$city] ?? 0;
                    }
                    $cityData[$province][$city]['adcode']        = $region[$city]['adcode'];
                    $cityData[$province][$city]['lng']           = $region[$city]['lng'];
                    $cityData[$province][$city]['lat']           = $region[$city]['lat'];

                    $this->info($city . '[市]' . '查询完成');
                }
            }
            foreach ($cityData as $k => $v) {
                if (isset($provinceData[$k]) && $provinceData[$k]) {
                    $provinceData[$k]['totalCity']           = count($v);//每个省对应下属市数量
                    $cityShopTotalNum                        = array_sum(array_column($v, 'shopNum'));
                    $cityCapacity                            = array_sum(array_column($v, 'capacity'));
                    $provinceData[$k]['cityPenetrationRate'] = $cityShopTotalNum > 0 && $cityCapacity > 0 ?
                        round($cityShopTotalNum * 100 / $cityCapacity, 2) . "%" : 0;//渗透率 = 门店总数/网规容量

                    //新增数据
                    $infoProvince = MapService::mapDataList('', '', $k);
                    collect($infoProvince)->each(function ($data, $bolt) use (&$provinceData, $k) {
                        $provinceData[$k][$bolt] = count($data);
                    });
                    if (in_array($k, array_keys($fixed))) {
                        $provinceData[$k]['recommendArea'] = $fixed[$k] ?? 0;
                    }
                    $this->info($k . '[省]' . '查询完成');
                }
            }
        }

        $total['penetrationRate'] = $total['shopTotalNum'] > 0 && $total['capacityTotalNum'] > 0 ?
            round($total['shopTotalNum'] * 100 / $total['capacityTotalNum'], 2) . "%" : 0;//渗透率 = 门店总数/网规容量

        $resAll = [
            'provinceData' => $provinceData,
            'cityData'     => $cityData,
            'total'        => $total,
        ];

        Cache::put('tiger:openShop:map:wangguiMapData', $resAll, now()->addDays(7));

        $this->info('添加缓存结果>>>>>' . Cache::has('wangguiMapData'));

        // $temp  = [];
        // $temp1 = 0;
        // foreach ($res as $vvv) {
        //     foreach ($vvv as $kk => $value) {
        //         if (!in_array($kk, ['省', '市', '区'])) {
        //             continue;
        //         }
        //         if (in_array($value, $temp)) {
        //             continue;
        //         }
        //         switch ($kk) {
        //             case '省':
        //                 $province = MapService::mapDataList('', '', $value);
        //                 Cache::store('file')->put('tiger:openShop:map:dataList:one:' . $value, $province, now()->addDays(7));
        //                 $this->info($value . '[省]');
        //                 $temp[] = $value;
        //                 break;
        //             case '市':
        //                 $city = MapService::mapDataList($value, '', '');
        //                 Cache::store('file')->put('tiger:openShop:map:dataList:two:' . $value, $city, now()->addDays(7));
        //                 $this->info($value . '[市]');
        //                 $temp[] = $value;
        //                 break;
        //             case '区':
        //                 $district = MapService::mapDataList('', $value, '');
        //                 Cache::store('file')->put('tiger:openShop:map:dataList:three:' . $value, $district, now()->addDays(7));
        //                 $this->info($value . '[区]');
        //                 $temp[] = $value;
        //                 break;
        //         }
        //         $this->info($value);
        //         $this->info(++$temp1);
        //     }
        // }

    }

    /**
     * 写死的网规数量
     * @return array
     */
    public static function fixed(): array
    {
        return [
            '上海市' => 590,
            '无锡市' => 212,
            '北京市' => 875,
            '广州市' => 395,
            '济南市' => 263,
            '深圳市' => 329,
            '江苏省' => 212,
            '广东省' => 724,
            '山东省' => 263,
        ];
    }

    public static function getCityAdcodeAndLocalPoint(): array
    {
        $provinceList = WangGuiCityByPower::getChinaDistrict();
        $city = [];
        foreach ($provinceList as $provinceSelf) {
            foreach ($provinceSelf['districts'] as $citySelf) {
                $city[str_replace('城区', '市', $citySelf['name'])] = [
                    'adcode' => $citySelf['adcode'],
                    'lng'    => explode(',', $citySelf['center'])[0],
                    'lat'    => explode(',', $citySelf['center'])[1],
                ];
            }
        }
        return $city;
    }
}
